package com._21cn.product.web.controller;

import com._21cn.cms.common.Constants;
import com._21cn.cms.common.FormSelector;
import com._21cn.framework.utils.StringUtil;
import com._21cn.product.entity.Cate;
import com._21cn.product.service.CateService;

import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.base.controller.BaseController;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/product/cate")
public class CateController extends BaseController{

	private static String listView = "/admin/product/cate/list";
    private static String showView = "/admin/product/cate/show";
    private static String jsonView = "/admin/product/cate/json";
    private static String formView = "/admin/product/cate/form";
    private static String redirectListView = "redirect:/admin/product/cate/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private CateService cateService;
	
	@Autowired(required = false)
    @Qualifier("cateValidator")
    private Validator cateValidator;

    @RequestMapping("/list")
    public String listCate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", listView);
        model.addAttribute( "statusMap", FormSelector.getStatusMap());
        model.addAttribute( "cateTypeMap", FormSelector.getCateTypeMap());
        setRequestModelMap( request, model, true );
        return view;
    }

    @RequestMapping("/search")
    public String searchCate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        Integer select = reqInfo.getIntParameter("select", 0);
        Integer typeId = reqInfo.getIntParameter("typeId", 0);
        setRequestModelMap( request, model, true );

        if(select.equals(1)){  //请求类型  1 接口、0普通
            Map<String, Object> resultMap = new HashMap<String,Object>();
            String ids = reqInfo.getParameter("ids", null);
            List<Integer> idList = StringUtil.str2IntList(ids);
            if( idList.size()>0 ){
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("inIdList", idList);
                params.put("eqStatus", Constants.STATUS_ENABLE);
                params.put("eqTypeId", typeId);
                List<Cate> list = cateService.getList(params, Constants.DEFAULT_FIRST_PAGE_NO, Constants.DEFAULT_PAGE_SIZE_COMMON);
                for(Cate cate : list){
                    resultMap.put(cate.getId()+"", cate.getName());
                }
            }
            model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(resultMap) );
            return view;
        }else {
            PageList<Cate> result = getPageList( model );
            model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
            return view;
        }
    }

    @RequestMapping("/show")
    public String showCate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", showView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            Cate cate = cateService.getById( id );
            if( cate == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
            model.addAttribute( "statusMap", FormSelector.getStatusMap());
            model.addAttribute( "cate", cate );
        }
        setRequestModelMap(request, model);
        return view;
    }

    @RequestMapping("/select")
    public String selectSite(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<Cate> result = getPageList( model );
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
        return view;
    }
	
	@RequestMapping("/edit")
    public String editCate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", formView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Cate cate = new Cate();
        if( id > 0 ){
            cate = cateService.getById(id);
            if( cate == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
        }
        model.addAttribute( "cate", cate );
        model.addAttribute( "statusMap", FormSelector.getStatusMap());
        model.addAttribute( "cateTypeMap", FormSelector.getCateTypeMap());
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/save")
    public String saveCate(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id>0 ){                                         //更新
            Cate cate = cateService.getById( id );
            if( bind( request, cate, model,  cateValidator).hasErrors() ){
                return formView;
            }
            cateService.update( cate );
        }else{                                              //添加
            Cate cate = new Cate();
            if( bind( request, cate, model,  cateValidator).hasErrors() ){
                return formView;
            }
            cateService.insert( cate );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }
	
	@RequestMapping("/updateStatus")
    public String updateCateStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        if( status < 0 ){
            model.clear();
            return redirectListView+ "?" + reqInfo.getParameter( "queryParam", "" );
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            cateService.update( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/delete")
    public String deleteCate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            cateService.delete( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }
	
	private PageList<Cate> getPageList(ModelMap model) {
        if(model.containsKey("likeName"))
            model.put("likeName",model.get("likeName").toString().toLowerCase());

        model.addAttribute("orderByClause", "ID desc");
        PageList<Cate> cateList = cateService.getList( model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()) );
        for(Cate cate : cateList){
            Integer parentId = cate.getParentId();
            if(parentId!=null && parentId>0){
                Cate parent = cateService.getById(parentId);
                if(parent!=null){
                    Map<Integer, String> cateTypeMap = FormSelector.getCateTypeMap();
                    String parentStr = parentId + " - " + cateTypeMap.get(parent.getTypeId()) + " - "+ parent.getName();
                    cate.setParentStr(parentStr);
                }
            }
        }
        model.addAttribute( "cateList", cateList);
        model.addAttribute( "objList", cateList);
        model.addAttribute( "pageTurn", cateList.getPageTurn());
        model.addAttribute( "titleMap", getPropertyTitleMap() );
        return cateList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if( propertyTitleMap == null ){
			propertyTitleMap = new HashMap<String,String>();
			propertyTitleMap.put( "id", "id" );
			propertyTitleMap.put( "typeId", "typeId" );
			propertyTitleMap.put( "name", "name" );
			propertyTitleMap.put( "nameShort", "nameShort" );
			propertyTitleMap.put( "initialWord", "initialWord" );
			propertyTitleMap.put( "code", "code" );
			propertyTitleMap.put( "logo", "logo" );
			propertyTitleMap.put( "memo", "memo" );
			propertyTitleMap.put( "sortNum", "sortNum" );
			propertyTitleMap.put( "status", "status" );
			propertyTitleMap.put( "createTime", "createTime" );
			propertyTitleMap.put( "modifyTime", "modifyTime" );
        }
        return propertyTitleMap;
    }
}
